import 'server-only';
import { cookies } from 'next/headers';
import { getIronSession, SessionOptions } from 'iron-session';
import { sessionSecretKey } from './config';

export interface SessionData {
  userId: string;
  username: string;
  role: string;
  isLoggedIn: boolean;
}

export const sessionOptions: SessionOptions = {
  cookieName: 'token',
  password: sessionSecretKey,
  ttl: 60 * 60 * 24 * 7, // 7 days
  cookieOptions: {
    httpOnly: true,
    // secure: process.env.NODE_ENV === 'production', // 在生产环境中启用 HTTPS 时设置为 true
    secure: false,
    sameSite: 'lax',
    path: '/',
  },
};

/**
 * 加载会话 session
 * @example
 * ```js
 * const session = await loadSession();
 * session.isLoggedIn = true
 * session.username = 'xxx';
 * session.userId = 'xxx';
 * session.role = 'admin';
 * session.save(); // 保存会话
 * session.destroy(); // 销毁会话
 * ```
 */
export async function loadSession() {
  const cookieStore = await cookies();
  const session = await getIronSession<Partial<SessionData>>(cookieStore, sessionOptions);
  return session;
}
